package com.atguigu.spzx.manager.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.atguigu.spzx.manager.service.ValidateCodeService;
import com.atguigu.spzx.model.vo.system.ValidateCodeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Transactional
@Service
public class ValidateCodeServiceImpl  implements ValidateCodeService {


    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public ValidateCodeVo generateValidateCode() {

        //1、hutool包下的一个工具类 ， 图形的宽度，高度，位数，干扰线数量；  返回circleCaptcha
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(20, 40, 1, 0);

        //2、从circleCaptcha对象中解析两个属性
        String code = circleCaptcha.getCode();//4位字符（图形中的验证码）
        String imageBase64 = circleCaptcha.getImageBase64();//前端用于显示的图形验证码base64编码的字符串

        //3、四位验证码存储到redis中
        String codeKey = UUID.randomUUID().toString().replaceAll("-","");
        String key = "user:code:" + codeKey;
        String value = code;

        redisTemplate.opsForValue().set(key,value,60, TimeUnit.MINUTES);//没生成的一个验证码的有效时间5分钟


        //4、封装validateCodeVo
        ValidateCodeVo validateCodeVo = new ValidateCodeVo();
        validateCodeVo.setCodeKey(codeKey);//传递给前端，将来在登录时，前端还会将codeKey传递给登录接口，登录接口需要去查询redis中正确的验证码（key=user:code:codeKey）
        validateCodeVo.setCodeValue("data:image/png;base64," + imageBase64);//前端显示base64编码的图形，以固定的字符串开头（data:image/png;base64,）

        return validateCodeVo;
    }
}
